<template>
  <div class="singer" ref="singer">
    <listview :data="singerlist" @selectitem = "selectitem" ref="list"></listview>
    <router-view></router-view>
  </div>
</template>

<script>
import {getSinger} from "api/singer.js"
import {ERR_OK} from "api/config.js"
import Listview from 'base/listview/listview.vue'
import {Singer} from "commom/js/singer.js"
import {mapMutations} from "vuex";
import {playListMixin} from "commom/js/mixin.js"
const HOT_NAME = '热门';
const HOT_SINGER_LEN = 10;
export default {
  mixins:[playListMixin],
  data(){
    return{
      singerlist:[]
    }
  },
  created(){
    this._getSingerList()
  },
  methods:{
    handlePlayList(playList){
      const bottom = playList.length > 0 ? '60px' : '';
      this.$refs.singer.style.bottom = bottom;
      this.$refs.list.refresh();
    },
    selectitem(singer){
      this.$router.push({
        path: `/singer/${singer.id}`
      })
      this.setSinger(singer);
    },
    _getSingerList(){
      getSinger().then((res)=>{
       if(res.code === ERR_OK){
         this.singerlist = this._normalizeSinger(res.data.list);
       }
      })
    },
    _normalizeSinger(list){
      let map = {
        hot:{
          name:HOT_NAME,
          items:[]
        }
      }
      list.forEach((item,index)=>{
        if(index < HOT_SINGER_LEN){
          map.hot.items.push(new Singer({
            id:item.Fsinger_mid,
            name:item.Fsinger_name
          }))
        }
        let key = item.Findex;
        if(!map[key]){
          map[key] = {
            name:key,
            items:[]
          }
        }
        map[key].items.push(new Singer({
          id:item.Fsinger_mid,
            name:item.Fsinger_name
        }))
      })
      let ret = [];
      let hot = [];
      for(let key in map){
        let val = map[key]
        if(val.name.match(/[a-z,A-Z]/)){
          ret.push(val)        
        }else if(val.name === HOT_NAME){
          hot.push(val)
        }
      }
      ret.sort(function(a,b){
        return a.name.charCodeAt(0) - b.name.charCodeAt(0)
      })
      return hot.concat(ret)
    },
    ...mapMutations({
      setSinger:'SET_SINGER'
    })
  },
  components:{
    Listview
  }
}
</script>

<style lang="stylus" scoped>
.singer
  position: fixed;
  top: 88px;
  bottom: 0;
  width :100%;
</style>
